package day19.Exer;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

/**

 */

public class DomProducts {
    private static Scanner in = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("1.显示商品信息；2.查找商品；3.修改商品信息；4.顾客购物；5.增加商品；6.退出");
            System.out.println("请选择：");
            int chosen = in.nextInt();
            switch (chosen) {
                case 1: {
                    show();
                    break;
                }
                case 2: {
                    System.out.println("请输入要查找的商品编号");
                    int itemno = in.nextInt();
                    selectProduct(itemno);
                    break;
                }
                case 3: {
                    System.out.println("请输入要修改的商品编号");
                    int itemno = in.nextInt();
                    System.out.println("请输入修改后的数量");
                    int stockcount = in.nextInt();
                    amend(itemno, stockcount);
                    break;
                }
                case 4: {
                    System.out.println("请输入要购买的商品编号");
                    int itemno = in.nextInt();
                    System.out.println("请输入购买数量");
                    int num = in.nextInt();
                    System.out.println("应付金额：" + shop(itemno, num));
                    break;
                }
                case 5: {
                    System.out.println("请输入添加的商品编码");
                    int itemno=in.nextInt();
                    System.out.println("请输入添加的商品名称");
                    String name=in.next();
                    System.out.println("请输入添加的商品单价");
                    double price=in.nextDouble();
                    System.out.println("请输入添加的商品计价单位");
                    String unit=in.next();
                    System.out.println("请输入添加的商品库存");
                    int stockcount=in.nextInt();
                    System.out.println("请输入添加的商品工厂地址");
                    String factoryaddr=in.next();
                    System.out.println("请输入添加的商品是否折扣");
                    boolean discount=in.nextBoolean();
                    addProduct(itemno,name,price,unit,stockcount,factoryaddr,discount);
                    break;
                }
                case 6: {
                    return;
                }
                default: {
                    System.out.println("输入错误请，请重新输入");
                }

            }
        }
    }

    //1.显示商品信息
    public static void show() {
        {
            SAXReader reader = new SAXReader();
            Document doc = null;
            try {
                doc = reader.read(DomProducts.class.getClassLoader().getResourceAsStream("day19/products.xml"));
                List<Element> elementList = doc.getRootElement().elements("product");
                for (Element element : elementList) {
                    Products a = new Products();
                    a.setItemno(Integer.parseInt(element.elementText("itemno")));
                    a.setName(element.elementText("name"));
                    a.setPrice(Double.parseDouble(element.elementText("price")));
                    a.setUnit(element.elementText("unit"));
                    a.setStockcount(Integer.parseInt(element.elementText("stockcount")));
                    a.setFactoryaddr(element.attributeValue("factoryaddr"));
                    a.setDiscount(Boolean.parseBoolean(element.attributeValue("discount")));
                    System.out.println(a.toString());
                }
            } catch (DocumentException e) {
                e.printStackTrace();
            }

        }

    }

    //2、查找商品
    public static Products selectProduct(int itemno) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(DomProducts.class.getClassLoader().getResourceAsStream("day19/products.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        List<Node> nodeList = doc.selectNodes("/shop/product[itemno='" + String.valueOf(itemno) + "']");
        if (nodeList.size() == 0) {
            System.out.println("不存在");
            return null;
        } else {
            Element element = (Element) nodeList.get(0);
            Products a = new Products();
            a.setItemno(Integer.parseInt(element.elementText("itemno")));
            a.setName(element.elementText("name"));
            a.setPrice(Double.parseDouble(element.elementText("price")));
            a.setUnit(element.elementText("unit"));
            a.setStockcount(Integer.parseInt(element.elementText("stockcount")));
            a.setFactoryaddr(element.attributeValue("factoryaddr"));
            a.setDiscount(Boolean.parseBoolean(element.attributeValue("discount")));
            System.out.println(a.toString());
            return a;
        }
    }
    //3.修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；没有找到商品号，给出提示。

    public static void amend(int itemno, int stockcount) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(DomProducts.class.getClassLoader().getResourceAsStream("day19/products.xml"));
            List<Node> nodeList = doc.selectNodes("/shop/product[itemno='" + String.valueOf(itemno) + "']");
            if (nodeList.size() == 0) {
                System.out.println("修改失败");
            } else {
                Element element = (Element) nodeList.get(0);
                element.element("stockcount").setText(String.valueOf(stockcount));
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("utf-8");
                XMLWriter xw = new XMLWriter(new FileWriter("D:\\Users\\ld\\IdeaProjects\\Java高级\\src\\day19\\products.xml"), format);
                xw.write(doc);
                xw.flush();
                xw.close();
                System.out.println("修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //4.以products.xml作为基础，实现客户购买的方法，输入商品号和购买数量，计算应付金额，如果是折扣商品，打七折；如果购买数量超过库存量，给出提示；
    // 商品不存在，给出提示；购买成功，扣除相应的数量。最后输出应付款的金额。
    public static double shop(int itemno, int num) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(DomProducts.class.getClassLoader().getResourceAsStream("day19/products.xml"));

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        List<Node> nodeList = doc.selectNodes("/shop/product[itemno='" + String.valueOf(itemno) + "']");
        if (nodeList.size() == 0) {
            System.out.println("商品不存在");
            return 0;
        } else {
            Element element = (Element) nodeList.get(0);
            if ((Integer.parseInt(element.elementText("stockcount"))) < num) {
                System.out.println("抱歉库存不够了");
                return 0;
            } else {
                element.element("stockcount").setText(String.valueOf(Integer.parseInt(element.elementText("stockcount")) - num));
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("utf-8");
                try {
                    XMLWriter xw = new XMLWriter(new FileWriter("D:\\Users\\ld\\IdeaProjects\\Java高级\\src\\day19\\products.xml"), format);
                    xw.write(doc);
                    xw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (Boolean.parseBoolean(element.attributeValue("discount"))) {
                    return Double.parseDouble(element.elementText("price")) * num * 0.7;
                } else {
                    return Double.parseDouble(element.elementText("price")) * num;
                }
            }


        }
    }

    //5.增加新品
    public static void addProduct(int itemno, String name, double price, String unit, int stockcount, String factoryaddr, boolean discount) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(DomProducts.class.getClassLoader().getResourceAsStream("day19/products.xml"));
           List<Element>elementList=doc.getRootElement().elements("product");
            for (Element element : elementList) {
                if(Integer.parseInt(element.elementText("itemno"))==itemno){
                    System.out.println("添加失败，商品编码已存在");
                    return;
                }
                if((element.elementText("name").equals(name))){
                    System.out.println("商品名重复");
                    return;
                }
            }
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            Element product=doc.getRootElement().addElement("product");
            product.addElement("itemno").setText(String.valueOf(itemno));
            product.addElement("name").setText(name);
            product.addElement("price").setText(String.valueOf(price));
            product.addElement("unit").setText(unit);
            product.addElement("stockcount").setText(String.valueOf(stockcount));
            product.addAttribute("factoryaddr",factoryaddr);
            product.addAttribute("discount",String.valueOf(discount));
            XMLWriter xw = new XMLWriter(new FileWriter("D:\\Users\\ld\\IdeaProjects\\Java高级\\src\\day19\\products.xml"), format);
            xw.write(doc);
            xw.flush();
            xw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

